﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_Inventory_StockReturn : System.Web.UI.UserControl
{
    DBDataContext db;
    DatabaseHelper helper;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["Username"] != null)
            {
                ResetForm();
            }
        }
    }
    private void loadProvince()
    {
        try
        {
            //Load tinh thanh 
            int ProvinceID = Session["ProvinceID"] == null ? 0 : int.Parse(Session["ProvinceID"].ToString());
            int isProvinceAll = (ProvinceID == 0 ? 1 : 0);
            Utils.loadLocation(cbProvince, 0, isProvinceAll, ProvinceID);//Tao moi
            Utils.loadLocationSearch(cbProvinceSearch, 0, isProvinceAll, ProvinceID);//Search
            //Load shop
            loadShop(ProvinceID, ProvinceID);

        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-LoadProvince:" + ex.Message);
        }
    }
    private void loadShop(int ProvinceID = -1, int ProvinceIDSearch = -1)
    {
        try
        {
            //load Shop
            int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
            int isShopAll = (ShopID == 0 ? 1 : 0);
            Utils.loadShopByProvinceToCombo(cbShop, isShopAll, ProvinceID, ShopID, "W");//Tao moi
            Utils.loadShopByProvinceToComboSearch(cbShopSearch, isShopAll, ProvinceIDSearch, ShopID, "W"); //Tim kiem
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-loadShop:" + ex.Message);
        }
    }
    private void ResetForm()
    {
        try
        {
           
            //Load Tinh thanh
            loadProvince();
            //Load san pham
            loadProductOfWarehouse();
            Utils.loadVendorToCombo(cbVendor, 0);
            gvProduct.DataSource = new DataTable();
            gvProduct.DataBind();
            rdpDate.SelectedDate = DateTime.Now.Date;
            rtpFromDateSearch.SelectedDate = DateTime.Now.Date;
            rtpToDateSearch.SelectedDate = DateTime.Now.Date;
            txtReturnCode.Text = GernerateCode();
            txtLastUpdatedBy.Text = Session["Username"].ToString();
            txtLastUpdatedDateTime.Text = DateTime.Now.ToString("dd/MM/yyyy");
            //Button
            btnCancel.Enabled = false;
            btnReturn.Enabled = false;
            
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-loadForm:" + ex.Message);
        }
    }
    private void resetGrid()
    {
        ViewState["TBLReturnDetail"] = null;
        divTotalQuantity.InnerText = "Tổng số lượng: 0";
        divTotalWeight.InnerText = "Tổng trọng lượng: 0 Kg";
        divGetTotalQuantity.InnerText = "";
        divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
        divGetTotalAmount.InnerText = "";

        gvProduct.DataSource = new DataTable();
        gvProduct.DataBind();
        txtQuantity.Text = "";
    }
    private void SetStatus(string strStatus)
    {
        if (strStatus == "R" || strStatus == "I")//Da tra hang
        {
            ////Button
            btnAdd.Enabled = false;
            btnNew.Enabled = true;
            btnSave.Enabled = false;
            btnCancel.Enabled = false;
            cbProvince.Enabled = false;
            btnReturn.Enabled = false;
            ////Combo
            cbShop.Enabled = false;
            cbVendor.Enabled = false;
            //cbType.Enabled = false;
            gvProduct.Enabled = false;
            cbProduct.Enabled = false;
        }
        if (strStatus == "N")
        {// Tao moi 
            btnCancel.Enabled = true;
            btnAdd.Enabled = true;
            btnNew.Enabled = true;
            btnSave.Enabled = true;
            btnReturn.Enabled = true;
            //Combo
            cbShop.Enabled = false;
            cbProvince.Enabled = false;
        }

    }
    private string GernerateCode()
    {
        string strCode = string.Empty;
        try
        {
            //Fortmat: LC00000001
            /*
         
              int lenZero = 7;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
                var customerCodeMax = dbread.Customers.Max(d => d.OrderNumber);
                int MaxOrderNumber = (customerCodeMax == null ? 0 : Convert.ToInt32(customerCodeMax)) + 1;
                String LastCode = ("000000" + MaxOrderNumber).ToString();
                String CustomerCode = "KH" + LastCode.Substring(LastCode.Length - lenZero);
             */

            db = new DBDataContext();
            var PurchaseOrderMax = db.Returns.Max(d => d.OrderNumber);
            int MaxOrderNumber = (PurchaseOrderMax == null ? 0 : Convert.ToInt32(PurchaseOrderMax)) + 1;
            String strLastCode = "00000000" + MaxOrderNumber.ToString();
            strCode = "TH" + strLastCode.Substring(strLastCode.Length - 8);
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-GernerateCode:" + ex.Message);
            ResetForm();
        }
        return strCode;
    }
    private DataTable createTable()
    {
        DataTable dt = null;
        try
        {
            if (ViewState["TBLReturnDetail"] == null)
            {
                dt = new DataTable();
                dt.Columns.Add("ProductID", System.Type.GetType("System.String"));
                dt.Columns.Add("PackType", System.Type.GetType("System.String"));
                dt.Columns.Add("ProductName", System.Type.GetType("System.String"));
                dt.Columns.Add("PurchasePrice", System.Type.GetType("System.Double"));
                dt.Columns.Add("Quantity", System.Type.GetType("System.Int32"));
                dt.Columns.Add("Weight", System.Type.GetType("System.Int32"));
                dt.Columns.Add("Amount", System.Type.GetType("System.Double"));
                //dt.Columns.Add("Delete");
            }
            else dt = (DataTable)ViewState["TBLReturnDetail"];
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-createTable:" + ex.Message.ToString());
        }
        return dt;
    }
    private void addDataToTable(ProStockReturn pro)
    {
        try
        {
            DataTable dt = createTable();
            //check ma san pham da chon chua, neu đa ton tai thi update

            DataRow[] rowArr = dt.Select("ProductID='" + pro.ProductID + "'");// Fortmar: ProductID | PackType
            if (rowArr.Count() > 0)
            {
                DataRow row = rowArr[0];
                row.Delete();
                dt.AcceptChanges();
            }

            DataRow drNew = dt.NewRow();
            string[] arr = pro.ProductID.Split('|');

            drNew["ProductID"] = pro.ProductID;
            drNew["PackType"] = arr[1];
            drNew["ProductName"] = pro.ProductName;
            drNew["PurchasePrice"] = Utils.KillChars(pro.PurchasePrice.Trim().Replace(",", ""));
            int iQuantity = Convert.ToInt32(Utils.KillChars(pro.Quantity.Trim().Replace(",", "")));
            drNew["Quantity"] = iQuantity;
            drNew["Weight"] = iQuantity * Convert.ToInt32(arr[1]);
            Double iAmount = Convert.ToDouble(pro.Quantity.Trim().Replace(",", "")) * Convert.ToDouble(pro.PurchasePrice.Trim().Replace(",", ""));
            drNew["Amount"] = iAmount;
            dt.Rows.Add(drNew);

            ViewState["TBLReturnDetail"] = dt;
            if (dt.Rows.Count > 0)
            {
                Double iTotalQuantity = Convert.ToInt32(dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Quantity"])));
                divTotalQuantity.InnerText = "Tổng số lượng: " + String.Format("{0:#,#.##}", iTotalQuantity);
                divGetTotalQuantity.InnerText = iTotalQuantity.ToString();
                divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:#,#.##}", dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Weight"]))) + " Kg";
                Double iTotalAmount = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Amount"])));
                divTotalAmount.InnerText = "Tổng tiền: " + String.Format("{0:#,#.##}", iTotalAmount) + " VNĐ";
                divGetTotalAmount.InnerText = iTotalAmount.ToString();
            }
            else
            {
                divTotalQuantity.InnerText = "Tổng số lượng: 0";
                divTotalWeight.InnerText = "Tổng trọng lượng: 0 Kg";
                divGetTotalQuantity.InnerText = "";
                divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
                divGetTotalAmount.InnerText = "";
            }
            
            gvProduct.DataSource = dt;
            gvProduct.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn-addDataToTable:" + ex.Message.ToString());
        }
    }
    private void loadProductOfWarehouse()
    {
        try
        {

            db = new DBDataContext();
            string strShopID = cbShop.SelectedValue.ToString();
            string strProductType = "R";
            strShopID = strShopID == "" ? "-1" : strShopID;
            cbProduct.Items.Clear();
            //if (strProductType == "R")
            //{
                var listProduct = (from a in db.Warehouses
                                   join b in db.Products on a.ProductID equals b.ID
                                   join c in db.CodeDetails on a.PackType.ToString() equals c.CDCode
                                   where a.Status == 'A' && a.Quantity > 0 && a.ShopID == Convert.ToInt32(strShopID) && b.ProductType == strProductType
                                   orderby b.ProductName
                                   select new
                                   {
                                       ProductName = b.ProductName,
                                       ProductID = b.ID + "|" + a.PackType,
                                       PackTypeName = c.CDName,
                                       PackType = a.PackType,
                                       ProductCode = b.ProductCode,
                                       PurchasePrice = a.PurchasePrice,
                                       ProductType = b.ProductType,
                                       Quantity = a.Quantity
                                   }
                ).ToList();
                foreach (var p in listProduct)
                {
                    RadComboBoxItem ra = new RadComboBoxItem();
                    if (p.Quantity > 0)
                    {
                        ra.Text = p.ProductCode + "-" +  p.ProductName + " (" + p.PackTypeName + " -SL tồn kho " + p.Quantity + ")";
                        ra.Value = p.ProductID.ToString();
                        cbProduct.Items.Add(ra);
                    }
                }
                DataTable dt = listProduct.ToDataTable();
                if (dt.Rows.Count > 0)
                    ViewState["dtWarehouse"] = dt;
           //}
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-loadProductOfWarehouse:" + ex.Message);
            ResetForm();
        }
    }
    private List<ReturnDetail> insertDetail(int iReturnDetail = 0)
    {
        try
        {
            List<ReturnDetail> listDetail = new List<ReturnDetail>();
            foreach (GridDataItem item in gvProduct.Items)
            {
                string[] arr = Utils.KillChars(item["ProductID"].Text.Trim()).Split('|');
                ReturnDetail soDetail = new ReturnDetail();
                soDetail.ReturnID = iReturnDetail;
                soDetail.ProductID = Convert.ToInt32(arr[0]);
                soDetail.PackType = Convert.ToInt32(arr[1]);//PackType
                string strPurchasePrice = Utils.KillChars(((Label)(item.FindControl("lblPurchasePrice"))).Text.Trim().Replace(",", ""));
                soDetail.PurchasePrice = Convert.ToDouble(strPurchasePrice == "" ? "0" : strPurchasePrice);
                string stQuantity = Utils.KillChars(((Label)(item.FindControl("lblQuantity"))).Text.Trim().Replace(",", ""));
                soDetail.Quantity = Convert.ToInt32(stQuantity == "" ? "0" : stQuantity);
                string strAmount = Utils.KillChars(((Label)(item.FindControl("lblAmount"))).Text.Trim().Replace(",", ""));
                soDetail.Amount = Convert.ToDouble(strAmount == "" ? "0" : strAmount);
                soDetail.CreatedBy = Session["UserName"].ToString();
                soDetail.LastUpdatedBy = Session["UserName"].ToString();
                soDetail.CreatedDateTime = DateTime.Now;
                soDetail.LastUpdatedDateTime = DateTime.Now;
                soDetail.Status = 'A';
                listDetail.Add(soDetail);
            }
            return listDetail;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-insertDetail:" + ex.Message);
            return null;
        }
    }
    private void deleteDetail(int iID = 0)
    {
        try
        {
            if (iID != 0)
            {
                List<ReturnDetail> soDetail = (from sd in db.ReturnDetails where sd.ReturnID == iID select sd).ToList<ReturnDetail>();
                db.Delete<ReturnDetail>(soDetail);
                //db.SubmitChanges();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-deletePurchaseOrderDetail:" + ex.Message.ToString());
        }
    }
    private bool save(ProStockReturn pro)
    {
        db = new DBDataContext();
        
        try
        {

            if (ViewState["ReturnID"] == null)//Insert INTO PurChaseOrder
            {
                using (var transation = new TransactionScope())
                {
                    try
                    {
                        string strCode = GernerateCode();
                        Return obj = new Return();
                        obj.ReturnCode = strCode;
                        obj.OrderNumber = Convert.ToInt32(Utils.KillChars(strCode.Substring(2, strCode.Length - 2)));
                        obj.ReturnDate = pro.dateTimeDate;
                        obj.ShopID = pro.iShopID;
                        obj.TotalAmount = pro.dTotalAmount;
                        obj.TotalQuantity = pro.iTotalQuantity;
                        obj.ProductType = pro.strType;
                        obj.VendorID = pro.iVendorID;
                        obj.Remark = pro.strRemark;
                        obj.CreatedBy = Session["Username"].ToString();
                        obj.CreatedDateTime = DateTime.Now;
                        obj.LastUpdatedBy = Session["Username"].ToString();
                        obj.LastUpdatedDateTime = DateTime.Now;
                        obj.Status = Convert.ToChar(pro.strStatus);
                        db.Insert<Return>(obj);
                        db.SubmitChanges();

                        ViewState["ReturnID"] = obj.ID;
                        db.Insert<ReturnDetail>(insertDetail(Convert.ToInt32(ViewState["ReturnID"])));
                        db.SubmitChanges();
                        transation.Complete();
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("StockReturn Page-Save-Transation-Status-N-ReturnID-" + ViewState["ReturnID"].ToString() + ":" + ex.Message);
                        transation.Dispose();
                        ViewState["ReturnID"] = null;
                        return false;
                    }
                }
            }
            else
            {
                Return obj = db.Returns.FirstOrDefault(x => x.ID == Convert.ToInt32(ViewState["ReturnID"]));
                obj.Remark = pro.strRemark;
                obj.LastUpdatedBy = Session["Username"].ToString();
                obj.LastUpdatedDateTime = DateTime.Now;

                if (pro.strStatus == "R")//Tinh trang Trả hàng
                {
                    using (var transation = new TransactionScope())
                    {
                        try
                        {
                            obj.TotalAmount = pro.dTotalAmount;
                            obj.TotalQuantity = pro.iTotalQuantity;
                            obj.ReturnDate = pro.dateTimeDate;
                            //db.SubmitChanges();
                            //Delete du lieu cu
                            deleteDetail(Convert.ToInt32(ViewState["ReturnID"]));
                            //Insert TransferWarsehouseDetail
                            db.Insert<ReturnDetail>(insertDetail(Convert.ToInt32(ViewState["ReturnID"])));
                            db.SubmitChanges();

                            //Tru kho
                            int iProductID = 0;
                            int iPackType = 0;
                            int? iQuantity = 0;
                            
                            List<Warehouse> listWarehouseSub = new List<Warehouse>();//List tru kho
                            var listDetail = (from a in db.ReturnDetails where a.Status == 'A' && a.ReturnID == Convert.ToInt32(ViewState["ReturnID"]) select a).ToList();
                            foreach (var a in listDetail)
                            {
                                iProductID = Convert.ToInt32(a.ProductID);
                                iPackType = Convert.ToInt32(a.PackType);
                                iQuantity = a.Quantity;
                                var subtractWarehouse = (from c in db.Warehouses
                                                         where c.ProductID == iProductID
                                                               && c.ShopID == obj.ShopID
                                                               && c.PackType == iPackType
                                                               && c.Status == 'A'
                                                         select c).FirstOrDefault();
                                if (subtractWarehouse != null)
                                {
                                    subtractWarehouse.Quantity = subtractWarehouse.Quantity - iQuantity;
                                    subtractWarehouse.RefCode = obj.ReturnCode;
                                    subtractWarehouse.RefType = "Trả hàng về NCC";
                                    subtractWarehouse.Remark = "Return";
                                    if (subtractWarehouse.Quantity <= 0)
                                    {
                                        subtractWarehouse.PurchasePrice = 0;
                                    }
                                    listWarehouseSub.Add(subtractWarehouse);
                                    //db.SubmitChanges();
                                }
                                //db.SubmitChanges();
                            }
                            //Tru kho
                            if (listWarehouseSub.Count > 0)
                            {
                                db.Insert<Warehouse>(listWarehouseSub);
                            }
                            obj.Status = Convert.ToChar(pro.strStatus);
                            db.SubmitChanges();
                            transation.Complete();
                        }
                        catch (Exception ex)
                        {
                            ControlUtil.LogError("StockReturn Page-Save-Transation-Status-R-ReturnID-" + ViewState["ReturnID"].ToString() + ":" + ex.Message);
                            transation.Dispose();
                            //ViewState["ReturnID"] = null;
                            return false;
                        }
                    }
                }
                if (pro.strStatus == "N")//Tao moi
                {
                    using (var transation = new TransactionScope())
                    {
                        try
                        {
                            obj.TotalAmount = pro.dTotalAmount;
                            obj.TotalQuantity = pro.iTotalQuantity;
                            obj.ReturnDate = pro.dateTimeDate;

                            //Delete du lieu cu
                            deleteDetail(Convert.ToInt32(ViewState["ReturnID"]));
                            //Insert lai moi
                            db.Insert<ReturnDetail>(insertDetail(Convert.ToInt32(ViewState["ReturnID"])));
                            db.SubmitChanges();
                            transation.Complete();
                        }
                        catch (Exception ex)
                        {
                            ControlUtil.LogError("StockReturn Page-Save-Transation-Status-N-ReturnID-" + ViewState["ReturnID"].ToString() + ":" + ex.Message);
                            transation.Dispose();
                            ViewState["ReturnID"] = null;
                            return false;
                        }
                    }
                }
                
            }
            //db.Transaction.Commit();
            return true;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-Save:" + ex.Message);
            //db.Transaction.Rollback();
            return false;
        }
    }
    private void loadData(ProStockReturn pro)
    {
        try
        {
            int PageNumber = gvData.CurrentPageIndex + 1;
            int PageSize = gvData.PageSize;

            helper = new DatabaseHelper();
            System.Data.Common.DbParameter paramID = helper.Parameter;
            paramID.ParameterName = "ReturnID";
            paramID.DbType = DbType.Int32;
            paramID.Value = -1;
            helper.AddParameter(paramID);

            System.Data.Common.DbParameter paramCode = helper.Parameter;
            paramCode.ParameterName = "ReturnCode";
            paramCode.DbType = DbType.String;
            paramCode.Value = pro.strCodeSearch;
            helper.AddParameter(paramCode);

            System.Data.Common.DbParameter paramShopID = helper.Parameter;
            paramShopID.ParameterName = "ShopID";
            paramShopID.DbType = DbType.Int32;
            paramShopID.Value = pro.iProvinceIDSearch;
            helper.AddParameter(paramShopID);

            System.Data.Common.DbParameter ProvinceID = helper.Parameter;
            ProvinceID.ParameterName = "ProvinceID";
            ProvinceID.DbType = DbType.Int32;
            ProvinceID.Value = pro.iProvinceIDSearch;
            helper.AddParameter(ProvinceID);

            System.Data.Common.DbParameter paramStatus = helper.Parameter;
            paramStatus.ParameterName = "Status";
            paramStatus.DbType = DbType.String;
            paramStatus.Value = pro.strStatusSearch;
            helper.AddParameter(paramStatus);

            System.Data.Common.DbParameter paramStartDate = helper.Parameter;
            paramStartDate.ParameterName = "StartDate";
            paramStartDate.DbType = DbType.String;
            paramStartDate.Value = pro.strStartDate;
            helper.AddParameter(paramStartDate);

            System.Data.Common.DbParameter paramEndDate = helper.Parameter;
            paramEndDate.ParameterName = "EndDate";
            paramEndDate.DbType = DbType.String;
            paramEndDate.Value = pro.strEndDate;
            helper.AddParameter(paramEndDate);

            System.Data.Common.DbParameter paramPageNumber = helper.Parameter;
            paramPageNumber.ParameterName = "PageNumber";
            paramPageNumber.DbType = DbType.Int32;
            paramPageNumber.Value = PageNumber;
            helper.AddParameter(paramPageNumber);

            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = PageSize;
            helper.AddParameter(paramPageSize);
            DataTable dt = helper.ExecuteDataTable("Admin_GetReturn", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            if (dt.Rows.Count > 0)
            {
                gvData.Height = 250;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
                gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
                gvData.VirtualItemCount = Convert.ToInt32(dt.Rows[0]["TotalRows"]);
                div_TotalRows.InnerText = "Kết quả tìm kiếm: " + String.Format("{0:N0}", dt.Rows[0]["TotalRows"]);
                gvData.DataSource = dt;
            }
            else
            {
                gvData.DataSource = new DataTable();
                div_TotalRows.InnerText = "Kết quả tìm kiếm: 0";
            }

            //gvData.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-loadData:" + ex.Message);
        }
    }
    private DataTable DTDetail(int iReturnID = 0)
    {
        //DataTable dt = null;
        try
        {
            db = new DBDataContext();
            var dtDetail = (from a in db.ReturnDetails
                                         join b in db.Products on a.ProductID equals b.ID
                                         where a.ReturnID == iReturnID && a.Status == 'A' && b.Status == 'A'
                                         select new
                                         {
                                             ProductID = b.ID + "|" + a.PackType,
                                             ProductName = b.ProductName + (a.PackType == 0 ? "" : " (" + a.PackType + " Kg)"),
                                             PackType = a.PackType,
                                             PurchasePrice = Convert.ToDouble(a.PurchasePrice),
                                             Amount = Convert.ToDouble(a.Amount),
                                             Quantity = a.Quantity,
                                             Weight = a.PackType * a.Quantity
                                         }).ToList();


            return dtDetail.ToDataTable();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-DTDetail:" + ex.Message.ToString());
            return new DataTable();
        }

    }
    private void getDataSearch()
    {
        ProStockReturn pro = new ProStockReturn();
        pro.strCodeSearch = Utils.KillChars(txtCodeSearch.Text.Trim());
        //pro.strTypeSearch = Utils.KillChars(cbTypeSearch.SelectedValue.Trim().ToString());
        pro.iShopID = Convert.ToInt32(Utils.KillChars(cbShopSearch.SelectedValue.Trim().ToString() == "0" ? "-1" : cbShopSearch.SelectedValue.Trim().ToString()));
        pro.iProvinceIDSearch = Convert.ToInt32(Utils.KillChars(cbProvinceSearch.SelectedValue.Trim().ToString() == "0" ? "-1" : cbProvinceSearch.SelectedValue.Trim().ToString()));
        pro.strStatusSearch = Utils.KillChars(cbStatusSearch.SelectedValue.Trim().ToString());
        pro.strStartDate = Utils.KillChars(this.rtpFromDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromDateSearch.SelectedDate));
        pro.strEndDate = Utils.KillChars(this.rtpToDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToDateSearch.SelectedDate));
        loadData(pro);
    }
    private void fillData(ProStockReturn pro)
    {
        try
        {
            txtReturnCode.Text = pro.strCode;
            cbShop.SelectedValue = pro.iShopID.ToString();
            cbVendor.SelectedValue = pro.iVendorID.ToString();
            //cbType.SelectedValue = pro.strType;
            rdpDate.SelectedDate = pro.dateTimeDate;
            txtStatus.Text = pro.strStatusName;
            txtRemark.Text = pro.strRemark;
            txtLastUpdatedBy.Text = pro.LastUpdatedBy;
            txtLastUpdatedDateTime.Text = pro.LastUpdatedDateTime;
            if (ViewState["ReturnID"] != null)
            {
                DataTable dt = DTDetail(Convert.ToInt32(ViewState["ReturnID"]));
                if (dt.Rows.Count > 0)
                {
                    ViewState["TBLReturnDetail"] = dt;
                    Double iTotalQuantity = Convert.ToInt32(dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Quantity"])));
                    divTotalQuantity.InnerHtml = "Tổng số lượng: " + String.Format("{0:#,#.##}", iTotalQuantity);
                    divGetTotalQuantity.InnerText = iTotalQuantity.ToString();
                    divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:#,#.##}", dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Weight"]))) + " Kg";
                    Double iTotalAmount = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Amount"])));
                    divTotalAmount.InnerHtml = "Tổng tiền: " + String.Format("{0:#,#.##}", iTotalAmount) + " VNĐ";
                    divGetTotalAmount.InnerText = iTotalAmount.ToString();

                }
                else
                {
                    divTotalQuantity.InnerText = "Tổng số lượng: 0";
                    divTotalWeight.InnerText = "Tổng trọng lượng: 0 Kg";
                    divGetTotalQuantity.InnerText = "";
                    divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
                    divGetTotalAmount.InnerText = "";
                }
                
                gvProduct.DataSource = dt;
                gvProduct.DataBind();
                div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}", gvProduct.Items.Count);
            }
            //loadProduct();
            SetStatus(pro.strStatus);
           //divStamp.Visible = false;

        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-fillData:" + ex.Message);
        }
    }
    protected void cbProvince_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (!cbProvince.SelectedValue.Trim().Equals("0") && !string.IsNullOrEmpty(cbProvince.SelectedValue.Trim()))
        {
            loadShop(Convert.ToInt32(cbProvince.SelectedValue.Trim()), Convert.ToInt32(cbProvinceSearch.SelectedValue.Trim()));
            loadProductOfWarehouse();
        }

        if (!cbProvinceSearch.SelectedValue.Trim().Equals("0") && !string.IsNullOrEmpty(cbProvinceSearch.SelectedValue.Trim()))
        {
            loadShop(Convert.ToInt32(cbProvince.SelectedValue.Trim()), Convert.ToInt32(cbProvinceSearch.SelectedValue.Trim()));
        }
    }
    //protected void cbType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    //{
    //    //loadProduct();
    //    //resetGrid();
    //}
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                if (gvProduct.Items.Count == 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chi tiết sản phẩm!");
                    cbProduct.Focus();
                    return;
                }
                ProStockReturn pro = new ProStockReturn();
                pro.strStatus = "R";
                pro.iShopID = Convert.ToInt32(Utils.KillChars(cbShop.SelectedValue.ToString() == "" ? "0" : cbShop.SelectedValue.ToString()));
                pro.iTotalQuantity = Convert.ToInt32(divGetTotalQuantity.InnerText.Trim() == "" ? "0" : divGetTotalQuantity.InnerText.Trim());
                pro.dTotalAmount = Convert.ToDouble(divGetTotalAmount.InnerText.Trim() == "" ? "0" : divGetTotalAmount.InnerText.Trim());
                pro.strRemark = Utils.KillChars(txtRemark.Text.Trim().ToString());
                pro.dateTimeDate = Convert.ToDateTime(Utils.KillChars(rdpDate.SelectedDate.ToString()));
                if (save(pro))
                {
                    txtStatus.Text = "Đã trả hàng";
                    SetStatus("R");
                    btnSave.Enabled = false;
                    btnAdd.Enabled = false;
                    btnCancel.Enabled = false;
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Đã trả hàng thành công!");
                   
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Trả hàng không thành công, vui lòng kiểm tra dữ liệu!");
                }
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("StockReturn Page-btnInput_Click:" + ex.Message.ToString());
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Trả hàng không thành công. Vui lòng kiểm tra dữ liệu và thực hiện lại!");
            }
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                ProStockReturn pro = new ProStockReturn();
               
                if (string.IsNullOrEmpty(cbProduct.SelectedValue))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn sản phẩm!");
                    cbProduct.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtQuantity.Text.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập số lượng!");
                    txtQuantity.Focus();
                    return;
                }
                if (txtQuantity.Text.Trim() == "0")
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng phải lớn hơn 0!");
                    txtQuantity.Focus();
                    return;
                }

                pro.ProductID =  Utils.KillChars(cbProduct.SelectedValue.Trim().ToString());
                pro.ProductName =  Utils.KillChars(cbProduct.SelectedItem.Text.Trim().ToString());
                pro.Quantity = Utils.KillChars(txtQuantity.Text.Trim());

                //Lay thong tin san pham
                if (ViewState["dtWarehouse"] != null)//Lay thong tin gia, check ton kho
                {
                    DataTable dt = (DataTable)ViewState["dtWarehouse"];
                    string strProductID = cbProduct.SelectedValue;
                    string iCount = dt.Rows.Count.ToString();
                    if (dt.Rows.Count > 0)
                    {
                        DataRow[] rowArr = dt.Select("ProductID='" + strProductID + "'");
                        if (rowArr.Count() > 0)
                        {
                            DataRow row = rowArr[0];
                            //if (ViewState["TBLTransferWarehouseDetail"] == null)
                            hidQuantity.Value = row["Quantity"].ToString();
                            hidPurchasePrice.Value = row["PurchasePrice"].ToString();//Lay gia san pham
                            hidProductName.Value = row["ProductCode"].ToString() + "-" + row["ProductName"].ToString();
                        }
                    }

                }
                if (Convert.ToInt32(txtQuantity.Text.ToString().Replace(",", "")) > Convert.ToInt32(hidQuantity.Value))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng nhập không lớn hơn số lượng tồn kho!");
                    txtQuantity.Focus();
                    return;
                }
                pro.PurchasePrice = hidPurchasePrice.Value;
                addDataToTable(pro);
                
                div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}", gvProduct.Items.Count);
                cbProduct.Enabled = true;
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("PurchaseOrderCreate Page-btnAdd_Click:" + ex.Message);
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Thêm không thành công, vui lòng thực hiện lại!");
            }
        }
    }
    protected void cbShop_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        //Load cua hang den
        if (!string.IsNullOrEmpty(cbShop.SelectedValue.ToString()))
        {
            
            //Load Product
            loadProductOfWarehouse();
            resetGrid();
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                if (string.IsNullOrEmpty(cbShop.SelectedValue.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn cửa hàng!");
                    cbShop.Focus();
                    return;
                }
                if (gvProduct.Items.Count == 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chi tiết sản phẩm!");
                    cbProduct.Focus();
                    return;
                }
                ProStockReturn pro = new ProStockReturn();
                pro.strStatus = "N";
                pro.iVendorID = Convert.ToInt32(cbVendor.SelectedValue.ToString() == "" ? "0" : cbVendor.SelectedValue.ToString());
                pro.dateTimeDate = Convert.ToDateTime(Utils.KillChars(rdpDate.SelectedDate.ToString()));
                pro.iShopID = Convert.ToInt32(Utils.KillChars(cbShop.SelectedValue.ToString() == "" ? "0" : cbShop.SelectedValue.ToString()));
                pro.iTotalQuantity = Convert.ToInt32(divGetTotalQuantity.InnerText.Trim() == "" ? "0" : divGetTotalQuantity.InnerText.Trim());
                pro.dTotalAmount = Convert.ToDouble(divGetTotalAmount.InnerText.Trim() == "" ? "0" : divGetTotalAmount.InnerText.Trim());
                pro.strRemark = Utils.KillChars(txtRemark.Text.Trim().ToString());
                pro.strType = "R";
                if (save(pro))
                {
                    txtStatus.Text = "Tạo mới";
                    SetStatus("N");
                    btnSave.Enabled = false;
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Lưu thành công!");
                    //string strStampRemain = StampQuantityRemain(Convert.ToInt32(ViewState["PurchaseOrderID"]));
                    //if (!string.IsNullOrEmpty(strStampRemain))
                    //{
                    //    lblStamRemain.Text = strStampRemain;
                    //    divStamp.Visible = true;
                    //}
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công, vui lòng kiểm tra dữ liệu!");
                }
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("StockReturn Page-btnSave_Click:" + ex.Message.ToString());
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công, vui lòng kiểm tra dữ liệu!");
            }
        }
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        //getDataSearch();
        gvData.Rebind();
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            if (ViewState["ReturnID"] != null)
            {

                db = new DBDataContext();
                Return obj = db.Returns.FirstOrDefault(x => x.ID == Convert.ToInt32(ViewState["ReturnID"]));
                obj.LastUpdatedBy = Session["Username"].ToString();
                obj.LastUpdatedDateTime = DateTime.Now;
                obj.Status = 'I';
                db.SubmitChanges();
                SetStatus("I");
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
            }
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        getDataSearch();
        gvData.DataBind();
    }
    protected void gvData_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                string commandName = e.CommandName;
                int ID = Convert.ToInt32(e.CommandArgument.ToString());//Lay ID 
                helper = new DatabaseHelper();
                ProStockReturn pro = new ProStockReturn();

                if (commandName == "EditItem")
                {
                    try
                    {
                        RadPageView1.Selected = true;
                        TabStrip1.SelectedIndex = 0;
                        System.Data.Common.DbParameter paramNewsID = helper.Parameter;
                        paramNewsID.ParameterName = "ReturnID";
                        paramNewsID.DbType = DbType.Int32;
                        paramNewsID.Value = ID;
                        helper.AddParameter(paramNewsID);
                        DataTable dt = helper.ExecuteDataTable("Admin_GetReturn", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                        if (dt.Rows.Count > 0)
                        {
                            pro.strCode = dt.Rows[0]["ReturnCode"].ToString();
                            pro.iShopID = Convert.ToInt32(dt.Rows[0]["ShopID"].ToString());
                            pro.iVendorID = Convert.ToInt32(dt.Rows[0]["VendorID"].ToString());
                            //pro.strType = dt.Rows[0]["ProductType"].ToString();
                            pro.strStatus = dt.Rows[0]["Status"].ToString();
                            pro.dateTimeDate = Convert.ToDateTime(dt.Rows[0]["ReturnDate"].ToString());
                            pro.strStatusName = dt.Rows[0]["StatusName"].ToString();
                            pro.dTotalAmount = Convert.ToDouble(dt.Rows[0]["TotalAmount"].ToString());
                            pro.iTotalQuantity = Convert.ToInt32(dt.Rows[0]["TotalQuantity"].ToString());
                            pro.strRemark = dt.Rows[0]["Remark"].ToString();
                            pro.LastUpdatedBy = dt.Rows[0]["LastUpdatedBy"].ToString();
                            pro.LastUpdatedDateTime = dt.Rows[0]["LastUpdatedDateTime"].ToString();
                            ViewState["ReturnID"] = ID;
                            fillData(pro);

                        }
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("StockReturn Page-gvData_ItemCommand-EditItem:" + ex.Message);
                    }
                }
                //else if (commandName == "DeleteItem")
                //{
                //    try
                //    {
                //        delete(ID);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
                //        gvData.Rebind();
                //    }
                //    catch (Exception ex)
                //    {
                //        ControlUtil.LogError("PurchaseOrder Page-gvData_ItemCommand-DeleteItem:" + ex.Message);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                //    }
                //}
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("StockReturn Page-gvData_ItemCommand:" + ex.Message);
            }
        }
    }
    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        try
        {
            ////Ham phan trang: Paging
            if (RadPageView3.Selected)
            {
                TabStrip1.SelectedIndex = 2;
                gvData.Height = 250;
                gvData.Visible = true;
                getDataSearch();
            }
            else
            {
                gvData.DataSource = new DataTable();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-gvData_NeedDataSource:" + ex.Message);
        }
    }
    protected void gvProduct_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        try
        {
            string commandName = e.CommandName;
            string strProductID = e.CommandArgument.ToString();//Lay ID 
            if (commandName == "EditItem")
            {
                //try
                //{
                //    DataTable dt = (DataTable)ViewState["TBLPurchaseOrderDetail"];
                //    DataRow[] rows = dt.Select("ProductID='" + strProductID + "'");
                //    if (rows.Count() > 0)
                //    {
                //        DataRow row = rows[0];
                //        txtPurchasePrice.Text = String.Format("{0:#,#.##}", row["PurchasePrice"]);
                //        txtQuantity.Text = String.Format("{0:#,#.##}", row["Quantity"]);
                //        cbProduct.SelectedValue = strProductID.ToString();
                //        cbProduct.Enabled = false;
                //        ViewState["TBLPurchaseOrderDetail"] = dt;
                //        div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}", gvProduct.Items.Count);
                //        gvProduct.DataSource = dt;
                //        gvProduct.DataBind();
                //    }
                //}
                //catch (Exception ex)
                //{
                //    ControlUtil.LogError("PurchaseOrderCreate Page-gvProduct_ItemCommand-EditItem:" + ex.Message);
                //}
            }
            else if (commandName == "DeleteItem")
            //if (commandName == "DeleteItem")
            {
                try
                {
                //    DataTable dt = (DataTable)ViewState["TBLPurchaseOrderDetail"];
                //    //DataRow[] rowArr = dt.Select("ProductID='" + strProductID + "'");
                //    DataRow[] rowArr = dt.Select("ProductID='" + strProductID + "'");
                //    if (rowArr.Count() > 0)
                //    {
                //        //string[] arr = cbProduct.SelectedValue.ToString().Split('|');
                //        //DataRow row = rowArr[0];
                //        //row["PurchasePrice"] = Utils.KillChars(txtPurchasePrice.Text.Trim().Replace(",", ""));
                //        //int iQuantity = Convert.ToInt32(row["Quantity"]) + Convert.ToInt32(Utils.KillChars(txtQuantity.Text.Trim().Replace(",", "")));
                //        //row["Quantity"] = iQuantity;
                //        //row["Weight"] = iQuantity * Convert.ToInt32(arr[1]);
                //        //Double iAmount = iQuantity * Convert.ToDouble(txtPurchasePrice.Text.Trim().Replace(",", ""));
                //        //row["Amount"] = iAmount;
                //        DataRow row = rowArr[0];
                //        if (row["PackType"] == "0")
                //            divTotalWeight.Visible = false;
                //        row.Delete();
                //        dt.AcceptChanges();
                //    }
                //    ViewState["TBLPurchaseOrderDetail"] = dt;
                //    if (dt.Rows.Count > 0)
                //    {
                //        Double iTotalQuantity = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Quantity"])));
                //        divTotalQuantity.InnerHtml = "Tổng số lượng: " + String.Format("{0:#,#.##}", iTotalQuantity);
                //        divGetTotalQuantity.InnerText = iTotalQuantity.ToString();
                //        divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:#,#.##}", dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Weight"]))) + " Kg";
                //        Double iTotalAmount = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Amount"])));
                //        divTotalAmount.InnerHtml = "Tổng tiền: " + String.Format("{0:#,#.##}", iTotalAmount) + " VNĐ";
                //        divGetTotalAmount.InnerText = iTotalAmount.ToString();
                //    }
                //    else
                //    {
                //        divTotalQuantity.InnerText = "Tổng số lượng: 0";
                //        divTotalWeight.InnerText = "Tổng trọng lượng: 0 Kg";
                //        divGetTotalQuantity.InnerText = "";
                //        divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
                //        divGetTotalAmount.InnerText = "";
                //    }

                //    div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}", gvProduct.Items.Count);
                //    gvProduct.DataSource = dt;
                //    gvProduct.DataBind();
                }
                catch (Exception ex)
                {
                    ControlUtil.LogError("PurchaseOrderCreate Page-gvProduct_ItemCommand-DeleteItem:" + ex.Message);
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                }
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrderCreate Page-gvProduct_ItemCommand:" + ex.Message);
        }
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("/StockReturn", false);
    }
    #region Properties
    public class ProStockReturn
    {
        public string strCode { get; set; }
        public DateTime dateTimeDate { get; set; }
        public string strRemark { get; set; }
        public string strType { get; set; }
        public string LastUpdatedBy { get; set; }
        public string LastUpdatedDateTime { get; set; }
        public int? iShopID { get; set; }
        public string strShopName { get; set; }
        public int? iVendorID { get; set; }
        public int? iOrderNumber { get; set; }
        public string strVendorName { get; set; }
        public string strStatus { get; set; }
        public string strStatusName { get; set; }
        public int? iPurchaseOrderPrice { get; set; }
        public int? iAmount { get; set; }
        public int? iQuantity { get; set; }
        public string PurchasePrice { get; set; }
        public string ProductID { get; set; }
        public string ProductName { get; set; }
        public string Quantity { get; set; }
        public int? iPackType { get; set; }
        public double? dTotalAmount { get; set; }
        public int? iTotalQuantity { get; set; }
        public string strStartDate { get; set; }
        public string strEndDate { get; set; }
        public string strTypeSearch { get; set; }
        public int? iShopIDSearch { get; set; }
        public int? iProvinceIDSearch { get; set; }
        public string strCodeSearch { get; set; }
        public string strStatusSearch { get; set; }
    }
    #endregion End Properties
}